/**
 * 屠宰
 * @constructor
 */
function Home4() {
}

Home4.init = function () {
    //初始化数据统计
    dataStatistics();
    //菜单显示
    authority();
    //公告
    $('#tableList4').bootstrapTable({
        url: '/noticeUsers/tableSearch',
        method: 'post',
        striped : true, //是否显示行间隔色
        toolbar: "#toolbar",
        sidePagination: "true",
        dataField: "data",//这是返回的json数组的key.默认是"rows".这里只有前后端约定好就行
        showToggle : false, //是否显示详细视图和列表视图的切换按钮
        striped: true, // 是否显示行间隔色
        //search : "true",
        uniqueId: "id",
        // pageList : [ 5, 10, 20,50,100],//可选择单页记录数
        pageSize: "5",
        pagination: true, // 是否分页
        sortable: false, // 是否启用排序
        sidePagination: 'server', // 设置为服务器端分页     客户端：client
        search:false,
        showColumns: false,
        showRefresh: false,
        showFooter:false,
        //得到查询的参数
        queryParams: function (params) {
            //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            var query_params = {
                //********table的参数 不变
                pageSize: params.limit,                         //页面大小
                pageIndex: (params.offset / params.limit) + 1,   //页码
                sort: params.sort,      //排序列名
                sortOrder: params.order, //排位命令（desc，asc）
                //********
                //获取查询的对象，往下加入
                status:0
            };
            return query_params;
        },
        columns:[
            {
                //field: 'Number',//可不加
                // title: '序号',//标题  可不加
                align: "center",
                width: 40,
                visible: false,
                formatter: function (value, row, index) {
                    var pageSize=$('#tableList4').bootstrapTable('getOptions').pageSize;//通过表的#id 可以得到每页多少条
                    var pageNumber=$('#tableList4').bootstrapTable('getOptions').pageNumber;//通过表的#id 可以得到当前第几页
                    return pageSize * (pageNumber - 1) + index + 1;//返回每条的序号： 每页条数 * （当前页 - 1 ）+ 序号
                }
            },
            {field: 'content', align: 'center'},
            {
                align: 'center',
                width: '15%',
                formatter:function(value,row,index){
                    let optionHtml = "<a class=\"btn btn-info btn-xs\"  href=\"javascript:void(0)\"  onclick='seeNotice(" + JSON.stringify(row) + ")'  title=\"查看\" >查看</a>";
                    return optionHtml;
                }
            },
        ]
    });
    //推送消息
    $('#tableList3').bootstrapTable({
        url: '/newsUsers/tableSearch',
        method: 'post',
        striped : true, //是否显示行间隔色
        toolbar: "#toolbar",
        sidePagination: "true",
        dataField: "data",//这是返回的json数组的key.默认是"rows".这里只有前后端约定好就行
        showToggle : false, //是否显示详细视图和列表视图的切换按钮
        striped: true, // 是否显示行间隔色
        //search : "true",
        uniqueId: "id",
        // pageList : [ 5, 10, 20,50,100],//可选择单页记录数
        pageSize: "5",
        pagination: true, // 是否分页
        sortable: false, // 是否启用排序
        sidePagination: 'server', // 设置为服务器端分页     客户端：client
        search:false,
        showColumns: false,
        showRefresh: false,
        showFooter:false,
        //得到查询的参数
        queryParams: function (params) {
            //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            var query_params = {
                //********table的参数 不变
                pageSize: params.limit,                         //页面大小
                pageIndex: (params.offset / params.limit) + 1,   //页码
                sort: params.sort,      //排序列名
                sortOrder: params.order, //排位命令（desc，asc）
                //********
                //获取查询的对象，往下加入
                status:0
            };
            return query_params;
        },
        columns:[
            {
                //field: 'Number',//可不加
                // title: '序号',//标题  可不加
                align: "center",
                width: 40,
                visible: false,
                formatter: function (value, row, index) {
                    var pageSize=$('#tableList3').bootstrapTable('getOptions').pageSize;//通过表的#id 可以得到每页多少条
                    var pageNumber=$('#tableList3').bootstrapTable('getOptions').pageNumber;//通过表的#id 可以得到当前第几页
                    return pageSize * (pageNumber - 1) + index + 1;//返回每条的序号： 每页条数 * （当前页 - 1 ）+ 序号
                }
            },
            {field: 'content', align: 'center'},
            {
                align: 'center',
                width: '15%',
                formatter:function(value,row,index){
                    let optionHtml = "<a class=\"btn btn-info btn-xs\"  href=\"javascript:void(0)\"  onclick='seeNews(" + JSON.stringify(row) + ")'  title=\"查看\" >查看</a>";
                    return optionHtml;
                }
            },
        ]
    });
    //待屠宰提醒
    $('#tableList1').bootstrapTable({
        url: '/home/slaughtered',
        method: 'post',
        striped : true, //是否显示行间隔色
        toolbar: "#toolbar",
        sidePagination: "true",
        dataField: "data",//这是返回的json数组的key.默认是"rows".这里只有前后端约定好就行
        showToggle : false, //是否显示详细视图和列表视图的切换按钮
        striped: true, // 是否显示行间隔色
        //search : "true",
        uniqueId: "id",
        // pageList : [ 5, 10, 20,50,100],//可选择单页记录数
        pageSize: "5",
        pagination: true, // 是否分页
        sortable: false, // 是否启用排序
        sidePagination: 'server', // 设置为服务器端分页     客户端：client
        search:false,
        showColumns: false,
        showRefresh: false,
        showFooter:false,
        //得到查询的参数
        queryParams: function (params) {
            //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            var query_params = {
                //********table的参数 不变
                pageSize: params.limit,                         //页面大小
                pageIndex: (params.offset / params.limit) + 1,   //页码
                sort: params.sort,      //排序列名
                sortOrder: params.order, //排位命令（desc，asc）
                //********
                //获取查询的对象，往下加入
            };
            return query_params;
        },
        columns:[
            {
                //field: 'Number',//可不加
                // title: '序号',//标题  可不加
                align: "center",
                width: 40,
                visible: false,
                formatter: function (value, row, index) {
                    var pageSize=$('#tableList1').bootstrapTable('getOptions').pageSize;//通过表的#id 可以得到每页多少条
                    var pageNumber=$('#tableList1').bootstrapTable('getOptions').pageNumber;//通过表的#id 可以得到当前第几页
                    return pageSize * (pageNumber - 1) + index + 1;//返回每条的序号： 每页条数 * （当前页 - 1 ）+ 序号
                }
            },
            { field: 'entryDate', title: '进厂日期',align: 'center'},
            { field: 'sourceAddress', title: '来源地址',align: 'center'},
            { field: 'ownerName', title: '畜主名称',align: 'center'},
            { field: 'type', title: '种类',align: 'center'},
            { field: 'quarantineNo', title: '检疫证号',align: 'center'},
            { field: 'livestock', title: '压栏数',align: 'center'},
            {
                title: '操作',
                align: 'center',
                formatter: function (value, row, index) {
                    var optionHtml = "";

                    optionHtml = optionHtml+"<a class=\"btn btn-info btn-xs\"  href=\"javascript:void(0)\"  onclick='actionRecord(" + JSON.stringify(row) + ",\"edit\")' title=\"屠宰\" ><i class=\"fa fa-edit\"></i>屠宰</a>";

                    return optionHtml;

                }
            }
        ]
    });
    //待出厂提醒
    $('#tableList2').bootstrapTable({
        url: '/home/exfactory',
        method: 'post',
        striped : true, //是否显示行间隔色
        toolbar: "#toolbar",
        sidePagination: "true",
        dataField: "data",//这是返回的json数组的key.默认是"rows".这里只有前后端约定好就行
        showToggle : false, //是否显示详细视图和列表视图的切换按钮
        striped: true, // 是否显示行间隔色
        //search : "true",
        uniqueId: "id",
        // pageList : [ 5, 10, 20,50,100],//可选择单页记录数
        pageSize: "5",
        pagination: true, // 是否分页
        sortable: false, // 是否启用排序
        sidePagination: 'server', // 设置为服务器端分页     客户端：client
        search:false,
        showColumns: false,
        showRefresh: false,
        showFooter:false,
        //得到查询的参数
        queryParams: function (params) {
            //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            var query_params = {
                //********table的参数 不变
                pageSize: params.limit,                         //页面大小
                pageIndex: (params.offset / params.limit) + 1,   //页码
                sort: params.sort,      //排序列名
                sortOrder: params.order, //排位命令（desc，asc）
                //********
                //获取查询的对象，往下加入
            };
            return query_params;
        },
        columns:[
            {
                //field: 'Number',//可不加
                // title: '序号',//标题  可不加
                align: "center",
                width: 40,
                visible: false,
                formatter: function (value, row, index) {
                    var pageSize=$('#tableList2').bootstrapTable('getOptions').pageSize;//通过表的#id 可以得到每页多少条
                    var pageNumber=$('#tableList2').bootstrapTable('getOptions').pageNumber;//通过表的#id 可以得到当前第几页
                    return pageSize * (pageNumber - 1) + index + 1;//返回每条的序号： 每页条数 * （当前页 - 1 ）+ 序号
                }
            },
            { field: 'entryDate', title: '进厂日期',align: 'center'},
            { field: 'sourceAddress', title: '来源地址',align: 'center'},
            { field: 'ownerName', title: '畜主名称',align: 'center'},
            { field: 'type', title: '种类',align: 'center'},
            { field: 'slaughterNumber', title: '数量',align: 'center'},
            { field: 'quarantineNo', title: '检疫证号',align: 'center'},
            {
                title: '操作',
                align: 'center',
                formatter: function (value, row, index) {
                    var optionHtml = "";

                    optionHtml = optionHtml+"<a class=\"btn btn-info btn-xs\"  href=\"javascript:void(0)\"  onclick='actionRecord1(" + JSON.stringify(row) + ",\"edit\")' title=\"出厂\" ><i class=\"fa fa-edit\"></i>出厂</a>";

                    return optionHtml;

                }
            }
        ]
    });
}
/**
 *时间选择器
 */
laydate.render({
    elem: '#childbirth_date',
    theme: 'molv',
    type:"date",
});
laydate.render({
    elem: '#text_ReportMonth',
    theme: 'molv',
    type:"month",
});
//出厂
function saveRecord() {
    if(!validateForm()) return false;
    var postdata = {
        slaughterId: slaughterId,
        entryRecordId: entryRecordId,
        action: Action,
        meatInspectionNo: $("#text_MeatInspectionNo").val(),
        flowAddress: $("#text_FlowAddress").val(),
        sellerName: $("#text_SellerName").val(),
        slaughterEarMark: slaughterEarMark,
    };
    //发送异步请求到后台保存用户数据
    $.ajax({
        url: "/factoryRecord/save",
        type: "post",
        data: JSON.stringify(postdata),
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            if (data.code === "200") {
                $('#myModalAdd').modal('hide')
                doSearch();
                swal("操作成功!", "请继续操作", "success");
            } else {
                swal("操作失败!", "请重试", "error");
            }
        }
    });
}
//查看公告
function seeNotice(data) {
    $.ajax({
        url: "/noticeUsers/read/"+data.id,
        type: "get",
        contentType: "application/json",
        dataType: "json",
        success: function (dat) {
            if (dat.code === "200") {
                $('#title').html(dat.data.title);
                $('#myContent').html(dat.data.content);
                $('#publisher').text(dat.data.userName);
                $('#publisheTime').text('       '+dat.data.noticeDate);
                if (data.enclosure != null && data.enclosure != ""){
                    $("#showEnclosure").show();
                    $("#downEnclosure").attr("href",dat.data.enclosure);
                }else {
                    $("#showEnclosure").hide();
                    $("#downEnclosure").attr("href","");
                }
                $('#myModalView').modal('show')
                $("#tableList4").bootstrapTable("refreshOptions",{pageNumber:1});
            }
        }
    });
}
//查看推送消息
function seeNews(data){
    $.ajax({
        url: "/newsUsers/read/"+data.id,
        type: "get",
        contentType: "application/json",
        dataType: "json",
        success: function (dat) {
            if (dat.code === "200") {
                $('#title1').html(dat.data.title);
                $('#myContent1').html(dat.data.content);
                $('#publisher1').text(dat.data.userName);
                $('#publisheTime1').text('       '+dat.data.createTime);
                $('#myModalView1').modal('show')
                $("#tableList3").bootstrapTable("refreshOptions",{pageNumber:1});
            }
        }
    });
}
//数据统计
function dataStatistics() {
    $.ajax({
        url: "/home/dataStatistics",
        type: "post",
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            $("#dataStatistics").empty();
            $("#dataStatistics").append("" +
                "                            <td class=\"text-center\">商品猪："+(data.day.commodity > 0 ? "<label style='color: red;font-weight: bold'>"+data.day.commodity+"</label>" : data.day.commodity)+"</td>\n" +
    "                                        <td class=\"text-center\">淘汰种猪："+(data.day.eliminate > 0 ? "<label style='color: red;font-weight: bold'>"+data.day.eliminate+"</label>" : data.day.eliminate)+"</td>\n" +
    "                                        <td class=\"text-center\">牛："+(data.day.cattle > 0 ? "<label style='color: red;font-weight: bold'>"+data.day.cattle+"</label>" : data.day.cattle)+"</td>\n" +
    "                                        <td class=\"text-center\">羊："+(data.day.sheep > 0 ? "<label style='color: red;font-weight: bold'>"+data.day.sheep+"</label>" : data.day.sheep)+"</td>\n" +
    "                                        <td class=\"text-center\">家禽："+(data.day.poultry > 0 ? "<label style='color: red;font-weight: bold'>"+data.day.poultry+"</label>" : data.day.poultry)+"</td>\n" +
    "\n" +
    "                                        <td class=\"text-center\">商品猪："+(data.stayDie.commodity > 0 ? "<label style='color: red;font-weight: bold'>"+data.stayDie.commodity+"</label>" : data.stayDie.commodity)+"</td>\n" +
    "                                        <td class=\"text-center\">淘汰种猪："+(data.stayDie.eliminate > 0 ? "<label style='color: red;font-weight: bold'>"+data.stayDie.eliminate+"</label>" : data.stayDie.eliminate)+"</td>\n" +
    "                                        <td class=\"text-center\">牛："+(data.stayDie.cattle > 0 ? "<label style='color: red;font-weight: bold'>"+data.stayDie.cattle+"</label>" : data.stayDie.cattle)+"</td>\n" +
    "                                        <td class=\"text-center\">羊："+(data.stayDie.sheep > 0 ? "<label style='color: red;font-weight: bold'>"+data.stayDie.sheep+"</label>" : data.stayDie.sheep)+"</td>\n" +
    "                                        <td class=\"text-center\">家禽："+(data.stayDie.poultry > 0 ? "<label style='color: red;font-weight: bold'>"+data.stayDie.poultry+"</label>" : data.stayDie.poultry)+"</td>\n" +
    "\n" +
    "                                        <td class=\"text-center\">商品猪："+(data.stayOut.commodity > 0 ? "<label style='color: red;font-weight: bold'>"+data.stayOut.commodity+"</label>" : data.stayOut.commodity)+"</td>\n" +
    "                                        <td class=\"text-center\">淘汰种猪："+(data.stayOut.eliminate > 0 ? "<label style='color: red;font-weight: bold'>"+data.stayOut.eliminate+"</label>" : data.stayOut.eliminate)+"</td>\n" +
    "                                        <td class=\"text-center\">牛："+(data.stayOut.cattle > 0 ? "<label style='color: red;font-weight: bold'>"+data.stayOut.cattle+"</label>" : data.stayOut.cattle)+"</td>\n" +
    "                                        <td class=\"text-center\">羊："+(data.stayOut.sheep > 0 ? "<label style='color: red;font-weight: bold'>"+data.stayOut.sheep+"</label>" : data.stayOut.sheep)+"</td>\n" +
    "                                        <td class=\"text-center\">家禽："+(data.stayOut.poultry > 0 ? "<label style='color: red;font-weight: bold'>"+data.stayOut.poultry+"</label>" : data.stayOut.poultry)+"</td>");
        }
    });
}
var Action="";
var Id=0;
var stype = "";
//操作相关方法****************************
function actionRecord(data,type) {
    //修改
    Id=data.id;
    Action="edit";
    $("#myform2")[0].reset();
    $("#save2").removeAttr("disabled");
    stype = data.type;
    // WriteData(data)
    $('#myModalAdd2').modal('show')
}
//给控件赋值****************************
function WriteData(data) {
    //初始化耳标号
    $.ajax({
        url:'/entryRecord/tableSearchEarmark/'+data.entryRecordId,
        type:"post",
        contentType:"application/json",
        dataType:"json",
        success:function(data){
            $("#text_Earmark").empty();
            $.each(data.data,function (index,o) {
                $("#text_Earmark").append("<label><input type=\"checkbox\" value=\""+o.earMarkNo+"\"/>"+o.earMarkNo+"</label>")
            })
        }
    });
}
//屠宰数据保存****************************
function saveRecord2() {
    if(!validateForm2()) return false;
    //创建传递的参数
    var postdata = {
        entryRecordId: Id,
        slaughterDate: $("#text_SlaughterDate").val(),   //屠宰日期
        slaughterNumber: $("#text_SlaughterNumber").val(),   //屠宰数量
        type:stype,
    };
    //发送异步请求到后台保存用户数据
    $.ajax({
        url:"/slaughterRecord/save",
        type:"post",
        data:JSON.stringify(postdata),
        contentType:"application/json",
        dataType:"json",
        success:function(data){
            if (data.code === "200") {
                $('#myModalAdd2').modal('hide')
                $("#tableList1").bootstrapTable("refreshOptions",{pageNumber:1});
                swal("操作成功!", "请继续操作", "success");
            } else if (data.code === "501"){
                swal("压栏数不足!", "请重试", "error");
            }else{
                swal("操作失败!", "请重试", "error");
            }
        }
    });
}
/**
 *时间选择器
 */
laydate.render({
    elem: '#text_SlaughterDate',
    theme: 'molv',
    type:"date",
});
//出厂
var Action = "";
var slaughterId = 0;
var slaughterEarMark = "";
var entryRecordId = ""
function actionRecord1(data, type) {
    //修改
    slaughterId = data.slaughterId;
    slaughterEarMark = data.slaughterEarMark;
    entryRecordId=data.entryRecordId;
    Action = "edit";
    $("#myform")[0].reset();
    $("#save").removeAttr("disabled");
    $('#myModalAdd').modal('show')
}
//出厂
function saveRecord1() {
    if(!validateForm()) return false;
    var postdata = {
        slaughterId: slaughterId,
        entryRecordId: entryRecordId,
        action: Action,
        meatInspectionNo: $("#text_MeatInspectionNo").val(),
        flowAddress: $("#text_FlowAddress").val(),
        sellerName: $("#text_SellerName").val(),
        slaughterEarMark: slaughterEarMark,
    };
    //发送异步请求到后台保存用户数据
    $.ajax({
        url: "/factoryRecord/save",
        type: "post",
        data: JSON.stringify(postdata),
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            if (data.code === "200") {
                $('#myModalAdd').modal('hide')
                $("#tableList2").bootstrapTable("refreshOptions",{pageNumber:1});
                swal("操作成功!", "请继续操作", "success");
            } else {
                swal("操作失败!", "请重试", "error");
            }
        }
    });
}
function validateForm2() {
    //validate方法参数可选
    return $("#myform2").validate({
        rules: {
            text_SlaughterDate: {
                required: true,//必填
                minlength: 1, //最少1个字符
            },
            text_SlaughterNumber: {
                required: true,//必填
                minlength: 1, //最少1个字符
                number: true, //必须是数字
            },
        },
        //错误信息提示
        messages: {
            text_SlaughterDate: {
                required: "(必填)",
                minlength: "最少1位",
            },
            text_SlaughterNumber: {
                required: "(必填)",
                minlength: "最少1位",
                number: "必须输入数字",
            },
        },
    }).form();
}
//出厂
function validateForm() {
    //validate方法参数可选
    return $("#myform").validate({
        rules: {
            text_FlowAddress: {
                required: true,//必填
                minlength: 1, //最少1个字符
            },
            text_SellerName: {
                required: true,//必填
                minlength: 1, //最少1个字符
            },
            text_MeatInspectionNo: {
                required: true,//必填
                minlength: 1, //最少1个字符
            },
        },
        //错误信息提示
        messages: {
            text_MeatInspectionNo: {
                required: "(必填)",
                minlength: "最少1位",
            },
            text_FlowAddress: {
                required: "(必填)",
                minlength: "最少1位",
            },
            text_SellerName: {
                required: "(必填)",
                minlength: "最少1位",
            },
        },
    }).form();
}

function authority() {
    $.ajax({
        url: "/home/authority",
        type: "post",
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            if (data == null){
                return false;
            }
            if (data.newsusers == 0){
                $("#newsusers").hide();
            }
            if (data.noticeUsers == 0){
                $("#noticeUsers").hide();
            }
            if (data.entryRecord == 0){
                $("#entryRecord").hide();
            }
            if (data.factoryRecord == 0){
                $("#factoryRecord").hide();
            }

        }
    });
}